﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
using KXmlUIControl.KControl;

namespace KXmlUIControl
{
    public class XmlKCheckBoxObject : XmlControlBase
    {
         /// <summary>
        /// 控件显示标题
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 控件标题颜色
        /// </summary>
        public Color TitleColor { get; set; }

        /// <summary>
        /// 控件表示的值
        /// </summary>
        public bool Checked { get; set; }

        /// <summary>
        /// CheckBox选中状态变化事件绑定委托的名称
        /// </summary>
        public string CheckedChanged { get; set; }

        public XmlKCheckBoxObject()
            : base()
        {

        }

        public override string ToXMLString()
        {
            return "";
        }

        private void SetCustomPropertyValue(KCheckBox cb)
        {
            cb.Title = Title;
            cb.TitleColor = TitleColor;
            cb.Checked = Checked;
        }

        public override void SetValues(Control ctl)
        {
            base.SetValues(ctl);
            SetCustomPropertyValue(ctl as KCheckBox);
        }

        public override Control ToControl(object parent)
        {
            KCheckBox control = new KCheckBox();
            SetValues(control);
            AddEventCheckedChanged(control, parent);
            return control;
        }

        private void AddEventCheckedChanged<T>(KCheckBox cb, T parent)
        {
            BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;
            if (!string.IsNullOrEmpty(CheckedChanged))
            {
                Type t = typeof(T);
                System.Reflection.MethodInfo methodInfo = t.GetMethod(CheckedChanged, flag);
                if (methodInfo != null)
                {
                    Delegate DelegateInstance = StaticTypes.CreateDelegateFromMethodInfoByDelegate<EventHandler>(parent, methodInfo);
                    if (DelegateInstance != null)
                    {
                        EventHandler handler = DelegateInstance as EventHandler;
                        cb.CheckedChanged += handler;
                    }
                }
            }
        }
    }
}
